package com.wgts.wgts.mvp.view.activity.guessing;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wgts.wgts.BuildConfig;
import com.wgts.wgts.R;
import com.wgts.wgts.base.BaseActivity;
import com.wgts.wgts.control.behavior.guessing.GuessingHeaderBehavior;
import com.wgts.wgts.control.dialog.RuleDialogFragment;
import com.wgts.wgts.dagger.ComponentHolder;
import com.wgts.wgts.dagger.component.DaggerGuessingActivityComponent;
import com.wgts.wgts.dagger.module.GuessingActivityModule;
import com.wgts.wgts.mvp.presenter.IGuessingActivityPresenter;
import com.wgts.wgts.mvp.view.IGuessingActivityView;
import com.wgts.wgts.mvp.view.activity.login.LoginActivity;
import com.wgts.wgts.mvp.view.activity.main.MoHuMainActivity;
import com.wgts.wgts.mvp.view.activity.webactivity.WebActivity;
import com.wgts.wgts.netmodle.resp.GuessingListEntity;
import com.wgts.wgts.tools.AppInfor;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.wgts.wgts.control.statusBar.IsplayHelper.getScreenHeight;
import static com.wgts.wgts.control.statusBar.IsplayHelper.getStatusBarHeight;

/*
 *
 *
 *   data:2018/9/1417:49
 *
 */public class GuessingActivity extends BaseActivity implements GuessingHeaderBehavior.OnPagerStateListener, IGuessingActivityView {

    @BindView(R.id.guessing_image)
    ImageView guessingImage;
    @BindView(R.id.placeholder_view)
    View placeholderView;
    @BindView(R.id.guessing_alpha_back)
    ImageView guessingAlphaBack;
    @BindView(R.id.guessing_rule_ly)
    RelativeLayout guessingRuleLy;
    @BindView(R.id.header_pager)
    FrameLayout headerPager;
    @BindView(R.id.perch_view)
    View perchView;
    @BindView(R.id.guessing_back)
    ImageView guessingBack;
    @BindView(R.id.guessing_title)
    TextView guessingTitle;
    @BindView(R.id.guessing_hidden_ly)
    RelativeLayout guessingHiddenLy;
    @BindView(R.id.guessing_tab_ly)
    TabLayout guessingTabLy;
    @BindView(R.id.guessing_recycle)
    RecyclerView guessingRecycle;
    @BindView(R.id.my_guessing_ly)
    LinearLayout myGuessingLy;
    private LinearLayoutManager manager;
    //判读是否是recyclerView主动引起的滑动，true- 是，false- 否，由tablayout引起的
    private boolean isRecyclerScroll;
    //用于recyclerView滑动到指定的位置
    private boolean canScroll;
    private int scrollToPosition;
    //记录上一次位置，防止在同一内容块里滑动 重复定位到tablayout
    private int lastPos;

    private GuessingHeaderBehavior mPagerBehavior;

    private List<GuessingListEntity> guessingList;

    @Inject
    IGuessingActivityPresenter presenter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.guessing_activity);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public void init() {
        DaggerGuessingActivityComponent
                .builder()
                .appComponent(ComponentHolder.getInstance().getAppComponent())
                .guessingActivityModule(new GuessingActivityModule(this))
                .build()
                .inject(this);
        guessingList = new ArrayList<>();
    }

    private void initView() {
        presenter.initList();
    }

    private void initRecycleView(){
        guessingTabLy.removeAllTabs();
        for (int i = 0; i < guessingList.size(); i++) {
            guessingTabLy.addTab(guessingTabLy.newTab().setText(guessingList.get(i).roundName));
        }
        for (int i = 0; i < guessingList.size(); i++) {
            TabLayout.Tab tab = guessingTabLy.getTabAt(i);//获得每一个tab
            tab.setCustomView(R.layout.guessing_tab_item);//给每一个tab设置view
            if (i == 0) {
                // 设置第一个tab的TextView是被选择的样式
                tab.getCustomView().findViewById(R.id.time_tab).setSelected(true);//第一个tab被选中
            }
            TextView time = (TextView) tab.getCustomView().findViewById(R.id.time);
            time.setText(guessingList.get(i).roundName + "人场");
            TextView type = (TextView) tab.getCustomView().findViewById(R.id.type);
            type.setText("满" + guessingList.get(i).roundName + "人开奖");
        }
        mPagerBehavior = (GuessingHeaderBehavior) ((CoordinatorLayout.LayoutParams)
                findViewById(R.id.header_pager).getLayoutParams()).getBehavior();
        mPagerBehavior.setPagerStateListener(this);
        manager = new LinearLayoutManager(this);
        int screenH = getScreenHeight(this);
        int statusBarH = getStatusBarHeight(this);
        int tabH = 100 * 3;
        int lastH = screenH - statusBarH - tabH;
        guessingRecycle.setLayoutManager(manager);
        guessingRecycle.setAdapter(new GuessingRecycleAdapter(guessingList, this, lastH));
    }

    private void tabSelect() {
        guessingTabLy.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //点击标签，使recyclerView滑动，isRecyclerScroll置false
                int pos = tab.getPosition();
                isRecyclerScroll = false;
                moveToPosition(manager, guessingRecycle, pos);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void moveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int position) {
        // 第一个可见的view的位置
        int firstItem = manager.findFirstVisibleItemPosition();
        // 最后一个可见的view的位置
        int lastItem = manager.findLastVisibleItemPosition();
        if (position <= firstItem) {
            // 如果跳转位置firstItem 之前(滑出屏幕的情况)，就smoothScrollToPosition可以直接跳转，
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 跳转位置在firstItem 之后，lastItem 之间（显示在当前屏幕），smoothScrollBy来滑动到指定位置
            int top = mRecyclerView.getChildAt(position - firstItem).getTop();
            mRecyclerView.smoothScrollBy(0, top);
        } else {
            // 如果要跳转的位置在lastItem 之后，则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
            // 再通过onScrollStateChanged控制再次调用当前moveToPosition方法，执行上一个判断中的方法
            mRecyclerView.smoothScrollToPosition(position);
            scrollToPosition = position;
            canScroll = true;
        }
    }

    private void recycleScrollChange() {
        guessingRecycle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当滑动由recyclerView触发时，isRecyclerScroll 置true
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    isRecyclerScroll = true;
                }
                return false;
            }
        });

        guessingRecycle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isRecyclerScroll) {
                    //第一个可见的view的位置，即tablayou需定位的位置
                    int position = manager.findFirstVisibleItemPosition();
                    if (lastPos != position) {
                        guessingTabLy.setScrollPosition(position, 0, true);
                    }
                    lastPos = position;
                }
            }
        });
    }

    private void tableLayoutChange() {
        guessingTabLy.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //点击标签，使recyclerView滑动，isRecyclerScroll置false
                int pos = tab.getPosition();
                isRecyclerScroll = false;
                moveToPosition(manager, guessingRecycle, pos);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        guessingRecycle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (canScroll) {
                    canScroll = false;
                    moveToPosition(manager, recyclerView, scrollToPosition);
                }
            }
        });
    }

    @OnClick({R.id.guessing_alpha_back, R.id.guessing_rule_ly, R.id.guessing_back, R.id.my_guessing_ly})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.guessing_alpha_back:
                finish();
                break;
            case R.id.guessing_rule_ly:
                Intent intent1 = new Intent(GuessingActivity.this, WebActivity.class);
                intent1.putExtra(WebActivity.TITLE, "规则");
                intent1.putExtra(WebActivity.ACTION_URL, "https://wap.mohuyoupin.com/hc_rule.html");
                startActivity(intent1);
//                RuleDialogFragment fragment = RuleDialogFragment.getAwardDialogFragment("展示的信息", RuleDialogFragment.GUESSING);
//                fragment.show(getSupportFragmentManager(), "GuessingDialog");
                break;
            case R.id.guessing_back:
                finish();
                break;
            case R.id.my_guessing_ly:
                if (AppInfor.getInstance().getRefreshToken() != null && !AppInfor.getInstance().getRefreshToken().equals("")){
                    Intent intent = new Intent(GuessingActivity.this, MyGuessingActivity.class);
                    startActivity(intent);
                }else {
                    Intent intent = new Intent(GuessingActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    @Override
    public void onPagerClosed() {
        if (BuildConfig.DEBUG) {
            Log.d("", "onPagerClosed: ");
        }
    }

    @Override
    public void onPagerOpened() {
        if (BuildConfig.DEBUG) {
            Log.d("", "onPagerOpened: ");
        }
    }

    @Override
    public void onBackPressed() {
        if (mPagerBehavior != null && mPagerBehavior.isClosed()) {
            mPagerBehavior.openPager();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onError(int status, String msg) {

    }

    @Override
    public void initList(List<GuessingListEntity> entities) {
        guessingList.clear();
        guessingList.addAll(entities);
        initRecycleView();
        tabSelect();
        recycleScrollChange();
        tableLayoutChange();
        //解决第一次进入页面第一个item展示不全
        moveToPosition(manager, guessingRecycle, 0);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        presenter.initList();
    }
}
